//
//  GYLock.m
//  LockManagement
//
//  Created by 丁燕春 on 2018/8/5.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYLock.h"
#import "GYNetWorkTools.h"


@implementation GYLock

+ (void)getLockListsWithlockName:(NSString *)lockName current:(NSString *)current pageSize:(NSString *)pageSize success:(void (^)(NSArray *))success error:(void (^)(NSError *))failed {
    NSString *IP = GETOBJ(@"IP")
    NSString *port = GETOBJ(@"port")
    [SVProgressHUD showWithStatus:@"正在加载钥匙列表..."];
    [GYNetWorkTools requestGetLocksListWithURL:[NSString stringWithFormat:@"http://%@:%@/api/getLocksList",IP,port] lockName:lockName current:current pageSize:pageSize success:^(NSDictionary *obj) {
        //NSLog(@"locklist===========%@",obj);
        int state = [[obj objectForKey:@"state"] intValue];
        if (state == 0) {
            NSArray *data = [obj objectForKey:@"data"];
            NSArray *tempArray = [self jsonLockListData:data];
            
            success(tempArray);
            
            //把这个数据储存起来
            NSString *filePath = [NSString CachesDir:@"lock.plist"];
            [obj writeToFile:filePath atomically:YES];
        }
        [SVProgressHUD dismiss];
    } error:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"加载数据失败,请重新加载!"];
        failed(error);
        NSLog(@"getlocklist  error====%@",error);
    }];
}

+ (NSArray *)jsonLockListData:(NSArray *)source {
    NSMutableArray *tempArray = [NSMutableArray array];
    for (NSDictionary *tempDic in source) {
        GYLock *lock = [[GYLock alloc] initWithDic:tempDic];
        [tempArray addObject:lock];
    }
    
    return tempArray;
}

- (void)lockCode:(NSString *)lockID lng:(float)lng lat:(float)lat success:(void (^)(BOOL))success error:(void (^)(NSError *))failed {
    NSString *IP = GETOBJ(@"IP")
    NSString *port = GETOBJ(@"port")
    [GYNetWorkTools requestLockCodeWithURL:[NSString stringWithFormat:@"http://%@:%@/api/lockCode",IP,port] lockID:lockID lng:lng lat:lat success:^(NSDictionary *obj) {
        NSLog(@"obj==========%@",obj);
        int state = [[obj objectForKey:@"state"] intValue];
        BOOL isSuccess = NO;
        if (state == 0) {
            isSuccess = YES;
        }
        success(isSuccess);
    } error:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"您的网络可能不太通畅..."];
        NSLog(@"lock code   error =====%@",error);
    }];
}

- (instancetype)initWithDic:(NSDictionary *)dic {
    self = [super init];
    if (self) {
        [self setValuesForKeysWithDictionary:dic];
    }
    
    return self;
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    
}

@end
